package com.example.administrator.myapplication.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.os.StatFs;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.example.administrator.myapplication.MyApplication;
import com.example.administrator.myapplication.NetConfig;
import com.example.administrator.myapplication.service.MyServerce;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author LiJL
 */
public class PublicTools {
    public final static String FileRootName = "/CarApp/";
    public final static String USERACTION = "fragment_update_data";
    public final static long DAYTIME = 1000 * 60 * 60 * 24;
    public final static String cookieName = "JSESSIONID";
    public static String result = null;
    //测试
//    public static String HTTP = "http://219.148.178.59:8081";
    //锡盟
//    public static String HTTP = "http://61.134.99.226:8080";

    /**
     * 推送给司机的待抢订单ID
     */
    public final static String WAITINGORDERID = "waiting_order_id";


    /**
     * 用户角色_司机
     */
    public static final String USER_ROLE_DRIVER = "DRIVER";

    /**
     * 用户角色_普通用户乘客
     */
    public static final String USER_ROLE_COMMAN = "common_user";


    /**
     * 微信相关信息结果广播
     */
    public final static String WECHATENTRY = "wechat_entry";
    /**
     * 微信支付结果通知广播
     */
    public final static String WECHATPAYENTRY = "wechat_pay_entry";

    /**
     * 最新版本信息文档地址
     */
    public static final String URL_CHECKVER = NetConfig.ROOT+"/appapk/android_nbd_app.json";

    /**
     * apk名称
     */
    public static final String LOAD_APK = "nbdapp.apk";

    /**
     * 包名
     */
    public static final String LOAD_PACKAGENAME = "com.yhjt.nbdapp";

    /**
     * 首页服务跳转id
     */
    public static final String HOME_SERVER_ID = "home_server_id";

    /**
     * 全场跳到商品详情的pistion
     * String
     */
    public static final String GOODS_DETAIL_POSITION = "position";
    /**
     * 全场跳到商品详情的id
     * String
     */
    public static final String GOODS_DETAIL_ID = "id";
    /**
     * order  position
     * String
     */
    public static final String ORDER_POSITION = "order_position";

    /**
     * 购物车跳转到确认订单的标记
     */
    public static final int SHOPCAE_INTENTINT = 102;
    /**
     * dindan 跳转到确认订单的标记
     */
    public static final int GOODS_ORDER = 104;
    /**
     * 购物车跳转到确认订单的标记
     */
    public static final String SHOPCAE_INTENTSTR = "shopcar";

    /**
     * 用来跳到商品详情的标记
     */
    public static final String GOODS_DETAIL_STR = "goodsId";
    /**
     * 用来跳到商品详情的标记
     */
    public static final int GOODS_DETAIL_GOODSID = 103;

    /**
     * 取SD卡路径
     *
     * @return
     */
    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory(); // 获取根目录
        }
        if (sdDir != null) {
            // System.out.println("Linsq--->"+sdDir.toString());
            return sdDir.toString();
        } else {
            return "";
        }
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static String getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "1.0";
        }
    }

    /**
     * 文件主目录
     *
     * @return
     */
    public static String getMainPath() {
        String path = getSDPath() + FileRootName;
        File dir = new File(path);
        if (!dir.exists())
            dir.mkdirs();
        return path;
    }

    public static String getImagePath() {
        String path = getSDPath() + FileRootName + "Image/";
        File dir = new File(path);
        if (!dir.exists())
            dir.mkdirs();
        return path;
    }

    public static String getImageCachePath() {
        String path = getSDPath() + FileRootName + "cache";
        File dir = new File(path);
        if (!dir.exists())
            dir.mkdirs();
        return path;
    }

    // 临时目录
    public static String getTempPath() {
        String path = getSDPath() + FileRootName + "thumbnails/";
        File dir = new File(path);
        if (!dir.exists())
            dir.mkdirs();
        return path;
    }

    /**
     * 删除文件主目录
     *
     * @param file
     * @param i
     */
    public static void deleteFolder(File file, int i) {
        if (file.isFile()) {
            file.delete();
            return;
        }
        if (file.isDirectory()) {
            File[] childFile = file.listFiles();
            if (childFile == null || childFile.length == 0) {
                if (i > 0)
                    file.delete();
                return;
            }
            for (File f : childFile) {
                deleteFolder(f, i + 1);
            }
            if (i > 0)
                file.delete();
        }
    }

    /**
     * 获取文件夹大小
     *
     * @param f
     * @return
     * @throws Exception
     */
    public static long getFileSize(File f) throws Exception// 取得文件夹大小
    {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSize(flist[i]);
            } else {
                size = size + flist[i].length();
            }
        }
        return size;
    }

    /**
     * Bitmap对象保存味图片文件
     *
     * @param bitmap
     */
    public static void saveBitmapFile(Bitmap bitmap, String filePath) {
        /**将要保存图片的路径*/
        File file = new File(filePath);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断所传入的文件是否大于SDcard剩余的容量
     *
     * @param fileSize
     * @return
     */
    public static boolean isComeInFile(long fileSize) {
        if ("".equals(getSDPath())) {
            Toast.makeText(MyApplication.getContext(), "SDcard不存在！",
                    Toast.LENGTH_SHORT).show();
            return false;
        } else {
            File path = Environment.getExternalStorageDirectory();
            StatFs statfs = new StatFs(path.getPath());
            long blockSize = statfs.getBlockSize();
            long availableBlocks = statfs.getAvailableBlocks();
            if (availableBlocks * blockSize > fileSize)
                return true;
            else {
                Toast.makeText(MyApplication.getContext(), "SDcard剩余容量不够",
                        Toast.LENGTH_SHORT).show();
                return false;
            }
        }
    }

    /**
     * 判断SDcard存在就为其创建文件夹
     *
     * @return
     */
    public static boolean craetAppFile() {
        if ("".equals(getSDPath())) {
            Toast.makeText(MyApplication.getContext(), "您的手机没有安装SDcard",
                    Toast.LENGTH_SHORT).show();
        } else {
            File file = new File(getImageCachePath());
            if (!file.isDirectory()) {
                file.mkdirs();
            }
            return true;
        }
        return false;
    }

    /**
     * 获取屏幕的长宽
     *
     * @return
     */
    public static Point getDisplayMetrics() {
        // String str = "";
        DisplayMetrics dm = new DisplayMetrics();
        dm = MyApplication.getContext().getResources().getDisplayMetrics();
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        Point a = new Point(screenWidth, screenHeight);
        return a;
    }

    /**
     * 设置输入框错误提示
     */
    public static void setEditTextError(EditText et, String str, int icon) {
        Drawable errorIcon = MyApplication.getContext().getResources()
                .getDrawable(icon);
        errorIcon.setBounds(new Rect(0, 0, errorIcon.getIntrinsicWidth(),
                errorIcon.getIntrinsicHeight()));// 设置图片大小
        if (str != null && str.length() > 0) {
            ForegroundColorSpan fgcspan = new ForegroundColorSpan(0xff454545);// 将提示文字
            // 改为红色
            SpannableStringBuilder ssbuilder = new SpannableStringBuilder(str);
            ssbuilder.setSpan(fgcspan, 0, str.length(), 0);
            et.setError(ssbuilder, errorIcon);
        } else
            et.setError(null, errorIcon);
        et.requestFocus();
    }

    /**
     * 减小图片大小
     *
     * @param srcPath
     * @param width
     * @param heigth
     * @return
     */
    public static File getimagePath(String srcPath, float width, float heigth, String filePath) {
        Bitmap bitmap = getimage(srcPath, width, heigth);
        // String fileName = PublicFunction.getFilePath() + "image"
        // + PublicFunction.getStrDate(System.currentTimeMillis())
        // + ".jpg";
        // 保存入sdCard
        File file2 = new File(filePath);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file2);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 50, out)) {
                out.flush();
            }
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
                out = null;
            }
        }
        return file2;
    }

    public static Bitmap getimage(String srcPath, float width, float heigth) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float ww = width;
        float hh = heigth;
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w >= h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// 设置缩放比例
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        ExifInterface exif;
        try {
            exif = new ExifInterface(srcPath);
            if (exif != null) { // 读取图片中相机方向信息
                int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_UNDEFINED);
                int digree = 0;
                switch (ori) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        digree = 90;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        digree = 180;
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        digree = 270;
                        break;
                }
                if (digree != 0) {
                    Matrix m = new Matrix();
                    m.postRotate(digree);
                    bitmap = Bitmap.createBitmap(bitmap, 0, 0,
                            bitmap.getWidth(), bitmap.getHeight(), m, true);
                }
            }
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        return bitmap;// 压缩好比例大小后再进行质量压缩
    }

    /**
     * 判断网络是否连接
     *
     * @param context
     * @return
     */
    public static boolean isConnect(Context context) {
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                // 获取网络连接管理的对象
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {
                    // 判断当前网络是否已经连接
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            Log.v("error", e.toString());
        }
        return false;
    }

    /**
     * 判断当前系统是否运行本程序
     *
     * @param activity
     * @return
     */
    public static boolean isTopActivity(Context activity) {
        String packageName = MyApplication.getContext().getPackageName();
        ActivityManager activityManager = (ActivityManager) activity
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
        if (tasksInfo.size() > 0) {
            System.out.println("---------------包名-----------"
                    + tasksInfo.get(0).topActivity.getPackageName());
            // 应用程序位于堆栈的顶层
            if (packageName.equals(tasksInfo.get(0).topActivity
                    .getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static String getVersion() {
        try {
            PackageManager manager = MyApplication.getContext()
                    .getPackageManager();
            PackageInfo info = manager.getPackageInfo(MyApplication
                    .getContext().getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /***
     * 生成6位随机数
     *
     * @return
     */
    public static int randomNum() {
        int n = 0;
        while (n < 100000) {
            n = (int) (Math.random() * 1000000);
        }
        return n;
    }

    /**
     * 控件的动画
     *
     * @param view
     */
    public static void Animshake(View view) {
        final TranslateAnimation anim = new TranslateAnimation(0, 10, 0, 0);

        // 利用 CycleInterpolator 参数 为float 的数 表示 抖动的次数，而抖动的快慢是由 duration 和
        // CycleInterpolator 的参数的大小 联合确定的
        anim.setInterpolator(new CycleInterpolator(6f));
        anim.setDuration(800);
        view.startAnimation(anim);
    }

    /**
     * 判断是不是手机号码
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern
                .compile("^1[345678][0-9]{9}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }
    /**
     * 判断用户名是不是汉字
     *
     * @param mobiles
     * @return
     */
    public static boolean isNormalUserNameNO(String mobiles) {
        Pattern p = Pattern
                .compile("^[a-zA-Z0-9_]{6,}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(int dpValue) {
        final float scale = MyApplication.getContext().getResources()
                .getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static void clearAllData() {
        // 清空数据库
//		SQLiteDBHelper.getInstance().deleteDatabase();
        // new SQLiteDBHelper(context).deleteDatabase(context);

        SharedPreferences preferences = null;
        SharedPreferences.Editor editor = null;
        preferences = MyApplication.getContext().getSharedPreferences(
                SharedPreFerencesTools.preferencesName, Context.MODE_PRIVATE);
        editor = preferences.edit();
        editor.clear();
        editor.commit();
        if (MyServerce.getInstance() != null) {
            MyServerce.getInstance().stopSubmmitLocation();
        }
    }

    /**
     * 获取指定Activity根RootView
     *
     * @param context
     * @return
     */
    public static View getRootView(Activity context) {
        return ((ViewGroup) context.findViewById(android.R.id.content))
                .getChildAt(0);
    }

    /**
     * 判断是否邮箱格式
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    /**
     * 隐藏键盘
     *
     * @param mcontext
     */
    public static void closeBoard(Context mcontext, View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) mcontext
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static byte[] packgeFile(List<File> files) throws Exception {
        if (files != null && !files.isEmpty()) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int size = files.size();
            writeInt(os, size);

            for (int i = 0; i < size; ++i) {
                File file = (File) files.get(i);
                String name = file.getName();
                byte[] nameByte = name.getBytes("UTF-8");
                writeInt(os, nameByte.length);
                os.write(nameByte);
                byte[] content = readFile(file);
                writeInt(os, content.length);
                os.write(content);
            }

            return os.toByteArray();
        } else {
            return new byte[0];
        }
    }

    public static void writeInt(OutputStream os, int data) throws Exception {
        byte hh = (byte) (data >> 24 & 255);
        byte hl = (byte) (data >> 16 & 255);
        byte lh = (byte) (data >> 8 & 255);
        byte ll = (byte) (data & 255);
        byte[] b4 = new byte[]{hh, hl, lh, ll};
        os.write(b4);
    }

    public static byte[] readFile(File file) throws Exception {
        FileInputStream in = new FileInputStream(file);
        int length = in.available();
        byte[] buffer = new byte[length];
        in.read(buffer);
        in.close();
        return buffer;
    }


    /**
     * 文件转化为字节数组
     *
     * @EditTime 2007-8-13 上午11:45:28
     */
    public static byte[] getBytesFromFile(File f) {
        if (f == null) {
            return null;
        }
        try {
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1) {
                out.write(b, 0, n);
            }
            stream.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
        }
        return null;
    }

    /**
     * 把字节数组保存为一个文件
     *
     * @EditTime
     */
    public static File getFileFromBytes(byte[] b, String outputFile) {
        BufferedOutputStream stream = null;
        File file = null;
        try {
            file = new File(outputFile);
            FileOutputStream fstream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fstream);
            stream.write(b);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return file;
    }

    /*时间戳转换成字符窜*/
    public static String getDateToString(long time) {
        Date d = new Date(time);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sf.format(d);
    }
    /*时间戳转换成字符窜*/
    public static String getDateToStringShort(long time) {
        Date d = new Date(time);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        return sf.format(d);
    }
    /*将字符串转为时间戳*/

    public static long getStringToDate(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        try {
            date = sdf.parse(time);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date.getTime();
    }

    public  static void dialog(){
        final ProgressDialog dialog;
//        dialog = ProgressDialogFactory.getProgressDialog(getActivity());
//        dialog.show();
    }
}